'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');

class DayService extends Service {
  /**
   * 根据分页和搜索条件获取用户信息
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条

   */
  async getPage(where, page, pageSize) {
      const { Day, Student, Course } = this.ctx.model;

      try {
          const res = Day.findAndCountAll({
              where: {
                  ...where
              },
              order:[
                  // id 降序
                  ['created_at','DESC']
              ],
              include: [
                  {model: Student, as: 'student'},
                  {model: Course, as: 'course'},
              ],
              offset: pageSize * (page - 1),
              limit: pageSize,
          });
          return res
      } catch (e) {
          console.log('00000', e)
      }
  }

  /**
   * 注册用户数据
   * @param {Object} data
   */
  async createItem(data) {
      const { Day } = this.ctx.model;
      const userExists = await Day.findOne({
          attributes: ['course_id', 'student_id'],
          where: {
              [Op.and]: {
                  course_id: data.course_id,
                  student_id: data.student_id,
              },
          },
      });
      console.log('userExists', userExists)
      if (userExists) throw new Error('该学生该课程已经打分');
      const newUser = await Day.create(data);
      return newUser.dataValues;
  }


    /**
   * 根据id删除对应的用户
   * @param {Number} uid
   */
  async deleteItemById(id) {
    return await this.ctx.model.Day.destroy({ where: { id } });
  }

  /**
   * 根据ID修改用户信息
   * @param {Number} id 用户ID
   * @param {Object} data 要修改的用户信息
   */
  async updateItemById(id, data) {
    const { Day } = this.ctx.model;
    const { day_name } = data;
    const andWhere = { id: { [Op.ne]: id } };
    let neenCheck = false;
   if (day_name) {
      neenCheck = true;
      andWhere.day_name = day_name;
    }

    if (neenCheck) {
      const userExists = await Day.findOne({
        attributes: ['id'],
        where: { [Op.and]: andWhere },
      });
      if (userExists) throw new Error('该账号已经存在');
    }

    return await Day.update(data, { where: { id } });
  }

  // 所有列表
  async allList(where) {
    const { Day } = this.ctx.model;
    return Day.findAll({
      where
    });
  }
}

module.exports = DayService;
